import { _decorator, Component, Input, input, EventMouse, Vec3, Animation, tween } from 'cc';
const { ccclass, property } = _decorator;

export const BLOCK_SIZE = 40; // 添加一个放大比

@ccclass('Player')
export class Player extends Component {

    private startJump: boolean = false;
    private jumpStep: number = 0;
    private curJumpTime: number = 0;
    private jumpTime: number = 0.1;
    private curJumpSpeed: number = 0;
    private curPos: Vec3 = new Vec3();
    private deltaPos: Vec3 = new Vec3(0, 0, 0);
    private targetPos: Vec3 = new Vec3();
    private curMoveIndex: number = 0;
    private jumpSpeedY: number = 0;

    @property(Animation)
    private bodyAnim: Animation = null;

    start() {
        console.log('Player start');
    }

    update(deltaTime: number) {
        if (this.startJump) {
            this.curJumpTime += deltaTime;
            if (this.curJumpTime > this.jumpTime) {
                this.node.setPosition(this.targetPos); // 直接设置到目标位置
                this.startJump = false;
                this.onOnceJumpEnd();
            } else {
                this.node.getPosition(this.curPos);
                this.deltaPos.x = this.curJumpSpeed * deltaTime;
                this.deltaPos.y = this.jumpSpeedY * deltaTime; // 添加 Y 轴速度
                Vec3.add(this.curPos, this.curPos, this.deltaPos);
                this.node.setPosition(this.curPos);
            }
        }
    }

    setInputActive(active: boolean) {
        if (active) {
            input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
            input.on(Input.EventType.MOUSE_MOVE, this.onMouseMove, this);
        } else {
            input.off(Input.EventType.MOUSE_UP, this.onMouseUp, this);
            input.off(Input.EventType.MOUSE_MOVE, this.onMouseMove, this);
        }
    }

    onMouseUp(event: EventMouse) {
        if (event.getButton() === 0) {
            this.jumpToMousePosition(event);
        }
    }

    onMouseMove(event: EventMouse) {
        if (event.getButton() === 0) {
            this.jumpToMousePosition(event);
        }
    }

    jumpToMousePosition(event: EventMouse) {
        if (this.startJump) {
            return;
        }
        this.startJump = true;
        this.curJumpTime = 0;

        const mousePos = event.getLocation();
        const worldPos = game.ui.canvas.cameraComponent.screenToWorld(new Vec3(mousePos.x, mousePos.y, 0));
        this.targetPos = worldPos.clone(); // 直接使用鼠标点击的位置作为目标位置

        const deltaX = worldPos.x - this.node.position.x;
        const deltaY = worldPos.y - this.node.position.y;

        // 判断移动方向
        const directionX = Math.sign(deltaX);
        const directionY = Math.sign(deltaY);

        // 根据方向选择动画
        let animName = '';
        const absDeltaX = Math.abs(deltaX);
        const absDeltaY = Math.abs(deltaY);
        if (directionX === 1 && directionY === 1) {
            if (absDeltaX > absDeltaY) {
                animName = 'jumpUpRightFromRight'; // 从右方移动到右上角
            } else if (absDeltaX < absDeltaY) {
                animName = 'jumpUpRightFromUp'; // 从上方移动到右上角
            } else {
                animName = 'jumpUpRight'; // 直线移动到右上角
            }
        } else if (directionX === -1 && directionY === 1) {
            if (absDeltaX > absDeltaY) {
                animName = 'jumpUpLeftFromLeft'; // 从左方移动到左上角
            } else if (absDeltaX < absDeltaY) {
                animName = 'jumpUpLeftFromUp'; // 从上方移动到左上角
            } else {
                animName = 'jumpUpLeft'; // 直线移动到左上角
            }
        } else if (directionX === 1 && directionY === -1) {
            if (absDeltaX > absDeltaY) {
                animName = 'jumpDownRightFromRight'; // 从右方移动到右下角
            } else if (absDeltaX < absDeltaY) {
                animName = 'jumpDownRightFromDown'; // 从下方移动到右下角
            } else {
                animName = 'jumpDownRight'; // 直线移动到右下角
            }
        } else if (directionX === -1 && directionY === -1) {
            if (absDeltaX > absDeltaY) {
                animName = 'jumpDownLeftFromLeft'; // 从左方移动到左下角
            } else if (absDeltaX < absDeltaY) {
                animName = 'jumpDownLeftFromDown'; // 从下方移动到左下角
            } else {
                animName = 'jumpDownLeft'; // 直线移动到左下角
            }
        } else if (directionX === 1 && directionY === 0) {
            animName = 'jumpRight'; // 向右移动
        } else if (directionX === -1 && directionY === 0) {
            animName = 'jumpLeft'; // 向左移动
        } else if (directionX === 0 && directionY === 1) {
            animName = 'jumpUp'; // 向上移动
        } else if (directionX === 0 && directionY === -1) {
            animName = 'jumpDown'; // 向下移动
        } else {
            animName = 'curveJump'; // 其他情况（曲线移动）
        }

        // 如果细分动画不存在，使用默认动画
        if (!this.bodyAnim.getState(animName)) {
            animName = 'curveJump';
        }
        console.log('animName:', animName);
        this.bodyAnim.play(animName);
        this.bodyAnim.once(Animation.EventType.FINISHED, () => {
            this.node.setPosition(this.targetPos); // 确保动画播放完毕后停在目标位置
            this.onOnceJumpEnd();
        });

        const state = this.bodyAnim.getState(animName);
        this.jumpTime = state.duration;
        // 计算移动速度
        this.curJumpSpeed = directionX * BLOCK_SIZE / this.jumpTime;
        this.jumpSpeedY = directionY * BLOCK_SIZE / this.jumpTime;

        // 直接使用线性插值
        tween(this.node)
            .to(this.jumpTime, { position: this.targetPos }, { easing: 'sineOut' })
            .start();

        this.curMoveIndex += directionX;
    }
        // 曲线运动逻辑
        // if (animName === 'curveJump') {
        //     const controlPoint = new Vec3(
        //         (this.curPos.x + this.targetPos.x) / 2,
        //         Math.max(this.curPos.y, this.targetPos.y) + BLOCK_SIZE * 1.5, // 提高控制点高度
        //         0
        //     );
        //     tween(this.node)
        //         .to(this.jumpTime, { position: this.targetPos }, {
        //             easing: 'sineOut',
        //             onUpdate: (target: any, ratio: number) => {
        //                 const pos = new Vec3();
        //                 // 使用二次贝塞尔曲线插值
        //                 Vec3.lerp(pos, this.curPos, controlPoint, ratio);
        //                 Vec3.lerp(pos, pos, this.targetPos, ratio);
        //                 this.node.setPosition(pos);
        //             }
        //         })
        //         .start();
        // } else {
            // tween(this.node)
            //     .to(this.jumpTime, { position: this.targetPos }, { easing: 'sineOut' })
            //     .start();
        // }


    reset() {
        this.curMoveIndex = 0;
        this.node.getPosition(this.curPos);
        this.targetPos.set(0, 0, 0);
    }

    onOnceJumpEnd() {
        this.node.emit('JumpEnd', this.curMoveIndex);
        this.moveCameraToTarget();
    }

    moveCameraToTarget() {
        const cameraNode = game.ui.playerCanvas.cameraComponent.node;
        if (!cameraNode) {
            console.error("Camera node is not available.");
            return;
        }

        const startPos = cameraNode.position;
        const endPos = this.node.position;

        const distance = Vec3.distance(startPos, endPos);
        if (distance === 0) {
            return;
        }

        const moveDuration = Math.min(1, distance / BLOCK_SIZE);

        // 增加延迟跟随效果
        const delayTime = 0.2; // 延迟 0.2 秒
        tween(cameraNode)
            .delay(delayTime)
            .to(moveDuration, { position: endPos }, { 
                easing: "sineOut",
                onUpdate: (target: any, ratio: number) => {
                    const currentPos = new Vec3();
                    Vec3.lerp(currentPos, startPos, endPos, ratio);
                    cameraNode.setPosition(currentPos);
                }
            })
            .start();
    }

    jump() {
        this.node.emit('JumpEnd', 1);
    }
}